<template>
  <view>
    <view class="container">
      <view class="info-row">
        <view class="name">订单总金额</view>
        <view class="money">
          <cn-money :money="info.totalAmount" :size="48"></cn-money>
        </view>
      </view>
      <view v-if="info.rows.length > 0">
        <view class="info-row" :key="index" v-for="(item, index) in info.rows">
          <view class="name">{{ item.payName }}</view>
          <view class="money">
            <cn-money :money="item.fee" :size="48"></cn-money>
          </view>
        </view>
      </view>
      <view class="info-row tipInfo"
        >服务过程中，如增加或者更换耗材，产生的费用将额外收费</view
      >
      <view class="pay-btn" @click="handleSubmit">确认并支付</view>
    </view>
  </view>
</template>

<script>
import * as orderInfo from '../../common/api/orderInfo.js'
import * as wxPay from '../../common/api/wxPay.js'
import cnMoney from '../../components/cn-money/cn-money'
import * as loginUtils from '../../utils/loginUtils.js'
export default {
  components: {
    cnMoney
  },
  data() {
    return {
      orderUid: '',
      orderNum: '',
	  orderNumber:'',
	  templateId: 'MM43WkRzz_BCBQti-dtKD1nnV1DEsGIPJ5fhVf84pJw',
	  openId:'ofuml6zQHd7CNukDGITkcdvVtApg',
      info: {},
      orderInfo: {},
    }
  },
  onLoad(opt) {
	console.log('opt',opt);
    this.orderNum = opt.orderNum
	this.orderNumber= opt.orderNum
    this.orderUid = opt.orderUid
    this.feeRules = opt.feeRules
    this.getOrderInfo()
    this.getData()
  },
  methods: {
    getData() {
      const param = {
        orderNum: this.orderNum,
        feeRules: this.feeRules
      }
      orderInfo.queryOrderPayItemSet(param).then(result => {
        this.info = result.data.data
      }).catch(error => {
        console.log(error);
      })
    },
    getOrderInfo() {
      const param = {
        uid: this.orderUid
      }
      orderInfo.queryById(param).then(result => {
        this.orderInfo = result.data.data
      }).catch(error => {
        console.log(error);
      })
    },
    handleSubmit() {
		this.subscribeMsg()
      if (!this.info) {
        console.log('info -> null');
        return
      }
      if (!this.orderInfo) {
        console.log('info -> null');
        return
      }
    },
    pay() {
      const orderInfo = this.orderInfo
      const info = this.info
      const param = {
        orderType: '护士上门',
        totalPrice: Number.parseFloat(info.totalAmount) * 100,
        goodsName: orderInfo.serviceItem,
        openId: uni.getStorageSync('openid_key'),
        orderSn: orderInfo.orderNum,
      }
      wxPay.createOrder(param).then(result => {
        const data = result.data.data
        const orderInfo = {
          appid: loginUtils.APPID, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
          nonceStr: data.nonceStr, // 随机字符串
          package: data.prepayId, // 固定值
          timeStamp: '' + data.timeStamp, // 时间戳（单位：秒）
          paySign: data.paySign, // 签名，这里用的 MD5/RSA 签名
          signType: 'HMAC-SHA256',
        }
        uni.requestPayment({
          provider: "wxpay",
          ...orderInfo,
          success(res) {
			  try {
				console.log('orderInfo',param.orderSn);
			    const res = uni.request({
			  		  // url: 'http://192.168.1.21:8050/applet/user/nurse/access/adminMessage',
			  	  url: 'https://applet.youtuyiliao.com/api/bedServer/nurse/access/adminMessage',
			      method: 'POST',
			      data: {
			        templateId: 'MM43WkRzz_BCBQti-dtKD1nnV1DEsGIPJ5fhVf84pJw',
			  		orderNumber:param.orderSn,
			      }
			    });
			  	console.log("item", res)
			    if (res.data.code === 0) {
			      uni.showToast({ title: '消息已发送' });
			    } else {
			      uni.showToast({ title: '发送失败', icon: 'none' });
			    }
			  } catch (error) {
			    console.error('请求后端失败:', error);
			  }
            console.log('支付成功', res);
            uni.showToast({
              icon: 'success',
              title: '支付成功',
              complete() {
                setTimeout(() => {
                  uni.navigateBack()
                }, 2000)
              }
            })
		
          },
          fail(err) {
            console.log('支付失败', err);
            uni.showToast({
              icon: 'none',
              title: '支付失败',
              complete() {

              }
            })
          }
        })
      }).catch(error => {
        console.log(error);
      })
    },
	subscribeMsg() {
		console.log('服务结束通知');
	  // 模板 ID 数组（可同时请求多个模板，但需用户逐一确认）
	  const templateIds = ['ECBQnn0plovzljftmioB9-wdyBncXQwcru9AF0hVxSs']; 
	  uni.requestSubscribeMessage({
	    tmplIds: templateIds,
	    success: (res) => {
	      // res 是对象，键为模板 ID，值为用户订阅结果：
	      // 'accept'（同意）、'reject'（拒绝）、'ban'（被封禁）
	      if (res['ECBQnn0plovzljftmioB9-wdyBncXQwcru9AF0hVxSs'] === 'accept') {
			  this.pay()
			  console.log('服务结束通知进来了');
	        // 用户同意订阅，触发后端发送消息
	        // this.sendMsgToServer();
	      } else {
	        uni.showToast({ title: '订阅失败，无法接收通知', icon: 'none' });
			this.pay()
	      }
	    },
	    fail: (err) => {
	      console.error('订阅失败:', err);
	      uni.showToast({ title: '订阅失败，请重试', icon: 'none' });
	    }
	  });
	},
  }
}
</script>
<style>
page {
  background: #f9f9f9;
}
</style>
<style lang="scss" scoped>
.info-row {
  display: flex;
  align-items: center;
  min-height: 80rpx;
  padding: 30rpx;
  background: white;
  border-bottom: solid 2rpx #f9f9f9;

  .name {
    flex: 1;
    font-weight: bold;
  }

  .money {
    // color: #60C8F5;
  }
}

.pay-btn {
  width: 100%;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #0bc5ae;
  color: white;
  border-radius: 48rpx;
  font-size: 30rpx;
  margin-top: 20rpx;
}

.container {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: 30rpx;
}

.tipInfo {
  color: blue;
  font-weight: bold;
}
</style>